package com.sicnu.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class ResponseSanitizerFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 先清理请求头
        exchange.getRequest().mutate()
                .headers(headers -> {
                    headers.remove("XSRF-TOKEN");
                    headers.remove("Set-Cookie");
                });

        return chain.filter(exchange).then(Mono.fromRunnable(() -> {
            // 统一响应头处理
            HttpHeaders headers = exchange.getResponse().getHeaders();
            headers.remove("Vary");
            headers.set("Vary", "Origin, Access-Control-Request-Method");

            // 确保只有一个 Set-Cookie
            if (headers.containsKey("SET-COOKIE")) {
                List<String> cookies = headers.get("SET-COOKIE");
                headers.set("SET-COOKIE", cookies.get(cookies.size() - 1));
            }

        }));
    }
}